var hprose = require("hprose");
var Fiber = require('fibers');
var tool_url = "http://api.dotnar.com/java_tools/";
var client = hprose.Client.create(tool_url + "checkCode");
var proxy = client.useService(["getCheckCode"]);
var codeCache = Object.create(null);
var imageCode = module.exports = {
	codeCache: codeCache,
	getImageCode: function(id) {
		var fiber = Fiber.current;
		var res;
		var vcode = codeCache[id] = Math.random().toString(36).substr(2, 4).toLowerCase();
		proxy.getCheckCode(vcode, function(result) {
			res = result.split(/[\n\r]/).join("");
			fiber.run();
		});
		Fiber.yield();
		return res;
	},
	getImageCodeBuff: function(id) {
		var base64_image_url = imageCode.getImageCode(id);
		var matches = base64_image_url.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
		var file_buffer = new Buffer(matches[2], 'base64');
		return file_buffer;
	},
	checkImageCode: function(id, vcode) {
		vcode = vcode.toLowerCase();
		return codeCache[id] == vcode;
	},
	CGImageCode: function(id) {
		return delete codeCache[id];
	}
};